package itv.java.web.util;

import itv.java.web.conf.Config;
import itv.java.web.log.Logger;

import java.util.List;

/**
 * @author : H-Thien
 * @comment : paging navigator
 */
public class PagingUtil {

	/**
	 * @comment :
	 */
	public static String getPaging(String currentPage, int totalRowCount,
			String rowPerPage) {
		String navigatorString = getPaging(currentPage, totalRowCount,
				rowPerPage, 10);

		return navigatorString;
	}

	/**
	 * @comment :
	 */
	public static String getPaging(String currnetPage, int totalRowCount,
			String rowPerPage, int nPage) {

		String navigatorString = "";

		int cPage = Integer.parseInt(currnetPage);
		int rPage = Integer.parseInt(rowPerPage);

		int totalPage = ((totalRowCount - 1) / rPage) + 1; // totalPage
		int startPage = ((cPage - 1) / nPage) * nPage + 1; // startPage

		// Previous Page
		if (startPage > 1) {
			int movePage = startPage - 1;
			navigatorString += "<a href='#' OnClick=\"javascript:pageMove('1');\"><<</a>&nbsp;<a href='#' OnClick=\"javascript:pageMove('"
					+ movePage + "');\"><</a>";
		} else {
			int movePage = startPage - 1;
			navigatorString += "<a ><<</a>&nbsp;<a ><</a>";
		}

		// Navigation Page
		for (int i = startPage; i < (startPage + nPage) && i <= totalPage; i++) {
			if (i == cPage) {
				navigatorString += "&nbsp;&nbsp;<font color='red'><strong>" + i
						+ "</strong></font>";
			} else {
				navigatorString += "&nbsp;&nbsp;<a href='#' OnClick=\"javascript:pageMove('"
						+ i + "');\">" + i + "</a>";
			}
		}

		// Next Page
		if (startPage + nPage - 1 < totalPage) {
			int movePage = startPage + nPage;
			navigatorString += "&nbsp;&nbsp;<a href='#' OnClick=\"javascript:pageMove('"
					+ movePage
					+ "');\">></A>&nbsp;<a href='#' OnClick=\"javascript:pageMove('"
					+ totalPage + "');\">>></a>";
		} else {
			int movePage = startPage + nPage;
			navigatorString += "&nbsp;&nbsp;<a >></A>&nbsp;<a >>></a>";
		}

		return navigatorString;
	}

	public static String getPagingListBox(String rowPerPage) throws Exception {
		StringBuffer str = new StringBuffer();
		String[] list = Config.getInstance().getString("project.row_per_page")
				.split(",");
		try {
			int listSize = list.length;
			for (int i = 0; i < listSize; i++) {
				if (list[i].equals(rowPerPage)) {
					str.append("<option value=\"" + list[i].toString()
							+ "\" selected>");
				} else {
					str.append("<option value=\"" + list[i].toString() + "\">");
				}
				str.append(list[i].toString() + " Rows");
				str.append("</option>");
			}
		} catch (Exception e) {
			Logger.error("[PagingUtil]getPagingListBox, Exception:" + e);
			throw new Exception(e);
		}
		return str.toString();
	}
}